﻿using NFL.DataAccess.Interface;
using NFL.DataModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace NFL.DataAccess.Implementation
{
    public abstract class Repository<T> : IRepository<T> where T : class
    {
        private NFLDataEntities dataContext;
        //NFLDataEntities _context = new NFLDataEntities();

        private readonly IDbSet<T> dbset;
        protected Repository(IDatabaseFactory databaseFactory)
        {

            DatabaseFactory = databaseFactory;
            dbset = (IDbSet<T>)DataContext.CreateObjectSet<T>();
            //dbset = (IDbSet<T>)DataContext.CreateObjectSet();
            //dbset = DataContext.CreateObjectSet<T>();
        }

        protected IDatabaseFactory DatabaseFactory
        {
            get;
            private set;
        }

        protected NFLDataEntities DataContext
        {
            get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
        }
        public virtual void Add(T entity)
        {
            dbset.Add(entity);
        }
        public virtual void Update(T entity)
        {
            //DatabaseContext _context = new DatabaseContext();
            dbset.Attach(entity);
            dataContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
        }
        public virtual void Delete(T entity)
        {
            dbset.Remove(entity);
        }
        public virtual void Delete(Expression<Func<T, bool>> where)
        {
            IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
            foreach (T obj in objects)
                dbset.Remove(obj);
        }
        public virtual T GetById(long id)
        {
            return dbset.Find(id);
        }
        public virtual T GetById(string id)
        {
            return dbset.Find(id);
        }
        public virtual IEnumerable<T> GetAll()
        {
            return dbset.ToList();
        }
        public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return dbset.Where(where).ToList();
        }
        public T Get(Expression<Func<T, bool>> where)
        {
            return dbset.Where(where).FirstOrDefault<T>();
        }
    }

}
